package com.syezon.wifikey.news.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;


import com.syezon.wifikey.api.ApiClient;
import com.syezon.wifikey.news.info.YiYouLiaoNewsTabBean;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class YiYouLiaoNewsTabViewModel extends AndroidViewModel {

    private MutableLiveData<List<YiYouLiaoNewsTabBean>> refreshMutableLiveData = new MutableLiveData<>();

    public YiYouLiaoNewsTabViewModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<List<YiYouLiaoNewsTabBean>> getRefreshMutableLiveData() {
        return refreshMutableLiveData;
    }

    public void getNewsTab() {
        ApiClient.getSelfNewsTab()
                .subscribeOn(Schedulers.io())
                .map(new Function<String, List<YiYouLiaoNewsTabBean>>() {
                    @Override
                    public List<YiYouLiaoNewsTabBean> apply(String s) throws Exception {
                        ArrayList<YiYouLiaoNewsTabBean> newsTabBeans = new ArrayList<>();
                        JSONObject jsonObject = new JSONObject(s);
                        // 返回json的数组
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            YiYouLiaoNewsTabBean newsTabBean = new YiYouLiaoNewsTabBean();
                            newsTabBean.setChannelName(jsonObject2.getString("channelName"));
                            newsTabBean.setChannelTag(jsonObject2.getString("channelTag"));
                            newsTabBeans.add(newsTabBean);
                        }
                        return newsTabBeans;
                    }
                })
                .subscribe(new DisposableObserver<List<YiYouLiaoNewsTabBean>>() {
                    @Override
                    public void onNext(List<YiYouLiaoNewsTabBean> s) {
                        refreshMutableLiveData.postValue(s);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}
